<!--
 * @Description: 
 * @Author: 胡涛
 * @Date: 2023-09-13 21:16:35
 * @LastEditors: 胡涛
 * @LastEditTime: 2024-01-04 22:40:24
-->
<template>
  <a-select
    :options="options"
    :value="value"
    @change="onValueChanged"
    v-bind="$props"
    placeholder="请选择用户信息"
    show-search
    :filter-option="filterOption"
  >
  </a-select>
</template>

<script lang="ts" setup>
import { computed } from "vue";
import { useDataStore } from "@/store";
import { storeToRefs } from "pinia";
import { EmptyGuid } from "@/helpers";

const emits = defineEmits([
  "update:value",
  "update:name",
  "update:phoneNumber",
  "update:email",
  "change",
]);

const props = defineProps({
  value: { type: [String] },
  name: { type: [String] },
  phoneNumber: { type: [String] },
  email: { type: [String] },
  roleName: { type: String },
  emptyText: { type: String },
  mode: { type: String },
  disabledIds: {
    type: Array,
    default: () => {
      return [];
    },
  },
});

const { userItems } = storeToRefs(useDataStore());

const options = computed(() => {
  let items: Array<{ label: string; value: string }> = [];
  if (props.roleName) {
    items = userItems.value
      .filter((x) => x.roleNames?.findIndex((r) => r == props.roleName) !== -1)
      .map((x) => {
        return {
          label: x.name,
          value: x.id,
          disabled: !!props.disabledIds?.find((id) => id == x.id),
        };
      });
  } else {
    items = userItems.value.map((x) => {
      return {
        label: x.name,
        value: x.id,
        disabled: !!props.disabledIds?.find((id) => id == x.id),
      };
    });
  }
  if (props.emptyText) {
    items.splice(0, 0, { label: props.emptyText, value: EmptyGuid });
  }
  return items;
});
const filterOption = (input: string, option: any) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

const onValueChanged = (value: string) => {
  let item = userItems.value.find((x) => x.id == value);
  emits("change", value);
  emits("update:value", value);
  emits("update:name", item?.name);
  emits("update:phoneNumber", item?.phoneNumber);
  emits("update:email", item?.email);
};
</script>

<style lang="less" scoped></style>
